package com.ly.heart.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.ly.common.core.domain.AjaxResult;
import com.ly.common.core.domain.entity.SysDept;
import com.ly.common.exception.CustomException;
import com.ly.common.utils.DateUtils;
import com.ly.common.utils.SecurityUtils;
import com.ly.common.utils.StringUtils;
import com.ly.common.utils.erp.ConstUtil;
import com.ly.common.utils.erp.ReturnPage;
import com.ly.common.utils.erp.SnowflakeIdWorker;
import com.ly.heart.domain.*;
import com.ly.heart.domain.dto.KingInquiryQueryDto;
import com.ly.heart.domain.dto.StartProcessDto;
import com.ly.common.core.domain.ActCurrentTaskVo;
import com.ly.heart.domain.vo.KingInquiryOfferVo;
import com.ly.heart.domain.vo.KingInquiryVo;
import com.ly.heart.mapper.KingInquiryMapper;
import com.ly.heart.service.*;
import com.ly.heart.util.ChineseToPinyin;
import com.ly.heart.util.CurrentUserUtil;
import com.ly.system.service.ISysDeptService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;

/**
 * 金蝶-询价/报价单Service业务层处理
 *
 * @author cxl
 * @date 2024-07-11
 */
@Service
public class KingInquiryServiceImpl extends ServiceImpl<KingInquiryMapper,KingInquiryEntity> implements IKingInquiryService {

    @Resource
    private KingInquiryMapper kingInquiryMapper;
    @Resource
    private ISysDeptService sysDeptService;
    @Resource
    private IKingInquirySupplierService inquirySupplierService;
    @Resource
    private IKingInquiryQuotationService inquiryQuotationService;
    @Resource
    private IKingInquiryDetailService inquiryDetailService;
    @Resource
    private IKingInquiryDetailEntryService inquiryDetailEntryService;
    @Resource
    private IActModelService actModelService;
    @Resource
    private IActTaskCommentService actTaskCommentService;
    @Resource
    private IKingBaseCurrencyService currencyService;


    @Override
    public AjaxResult draft(KingInquiryEntity kingInquiryEntity) {
        if(Objects.nonNull(kingInquiryEntity.getId())){
            int i = updateKingInquiryEntity(kingInquiryEntity);
            if(i == 1){
                return AjaxResult.success("暂存成功！");
            }
            return AjaxResult.error("暂存失败！");
        }
        if(CollectionUtils.isEmpty(kingInquiryEntity.getInquiryDetailList())){
            throw new RuntimeException("物料明细不能为空！");
        }
        String inquiryId = SnowflakeIdWorker.getInstance().nextStringId();
        Date nowDate = DateUtils.getNowDate();
        String userId = SecurityUtils.getLoginUser().getUser().getUserId();
        //保存适用供应商信息
        if(!CollectionUtils.isEmpty(kingInquiryEntity.getInquirySupplierList())){
            List<KingInquirySupplierEntity> inquirySupplierList = kingInquiryEntity.getInquirySupplierList();
            for(KingInquirySupplierEntity inquirySupplier : inquirySupplierList){
                inquirySupplier.setId(SnowflakeIdWorker.getInstance().nextStringId());
                inquirySupplier.setInquiryId(inquiryId);
                boolean save = inquirySupplierService.save(inquirySupplier);
                if(!save){
                    throw new RuntimeException("新增询价/报价单适用供应商信息失败！");
                }
            }
        }
        //保存报价采纳信息
        if(!CollectionUtils.isEmpty(kingInquiryEntity.getInquiryQuotationList())){
            List<KingInquiryQuotationEntity> inquiryQuotationList = kingInquiryEntity.getInquiryQuotationList();
            for(KingInquiryQuotationEntity inquiryQuotation : inquiryQuotationList){
                inquiryQuotation.setId(SnowflakeIdWorker.getInstance().nextStringId());
                inquiryQuotation.setInquiryId(inquiryId);
                boolean save = inquiryQuotationService.save(inquiryQuotation);
                if(!save){
                    throw new RuntimeException("新增询价/报价单报价采纳信息失败！");
                }
            }
        }
        //保存物料明细信息
        List<KingInquiryDetailEntity> inquiryDetailList = kingInquiryEntity.getInquiryDetailList();
        for(KingInquiryDetailEntity inquiryDetail : inquiryDetailList){
            String inquiryDetailId = SnowflakeIdWorker.getInstance().nextStringId();
            inquiryDetail.setInquiryId(inquiryId);
            inquiryDetail.setId(inquiryDetailId);
            inquiryDetail.setType(kingInquiryEntity.getType());
            boolean save = inquiryDetailService.save(inquiryDetail);
            if(!save){
                throw new RuntimeException("新增询价/报价单物料明细信息失败！");
            }
            if(Objects.nonNull(inquiryDetail.getInquiryDetailEntry())){
                KingInquiryDetailEntryEntity inquiryDetailEntry = inquiryDetail.getInquiryDetailEntry();
                inquiryDetailEntry.setId(SnowflakeIdWorker.getInstance().nextStringId());
                inquiryDetailEntry.setInquiryId(inquiryId);
                inquiryDetailEntry.setDetailId(inquiryDetailId);
                inquiryDetailEntryService.save(inquiryDetailEntry);
            }
        }
        //生成单号
        if(StringUtils.isEmpty(kingInquiryEntity.getDocCode())){
            if(kingInquiryEntity.getType().equals( ConstUtil.INQUIRY_TYPE_ASK)){
                String companyId = CurrentUserUtil.getCompanyId();
                SysDept sysDept = sysDeptService.getById(companyId);
                int count = this.count(new LambdaQueryWrapper<KingInquiryEntity>().eq(KingInquiryEntity::getType, ConstUtil.INQUIRY_TYPE_ASK));
                String countStr = String.format("%06d", count);
                String firstLetter = ChineseToPinyin.getFirstLetter(sysDept.getDeptName());
                String docCode = firstLetter.concat("_XJD_").concat(countStr);
                kingInquiryEntity.setDocCode(docCode);
            }
            if(kingInquiryEntity.getType().equals(ConstUtil.INQUIRY_TYPE_PROVIDE)){
                String companyId = CurrentUserUtil.getCompanyId();
                SysDept sysDept = sysDeptService.getById(companyId);
                int count = this.count(new LambdaQueryWrapper<KingInquiryEntity>().eq(KingInquiryEntity::getType, ConstUtil.INQUIRY_TYPE_PROVIDE));
                String countStr = String.format("%06d", count);
                String firstLetter = ChineseToPinyin.getFirstLetter(sysDept.getDeptName());
                String docCode = firstLetter.concat("_BJD_").concat(countStr);
                kingInquiryEntity.setDocCode(docCode);
            }
        }
        kingInquiryEntity.setCreateBy(userId);
        kingInquiryEntity.setCreateTime(nowDate);
        kingInquiryEntity.setId(inquiryId);
        //流程状态：暂存
        kingInquiryEntity.setState(ConstUtil.STATE_IN_DRAFT);
        boolean saveFlag = this.save(kingInquiryEntity);
        if (saveFlag) {
            return AjaxResult.success("暂存成功！");
        }
        return AjaxResult.error("暂存失败！");
    }

    @Override
    public AjaxResult submit(KingInquiryEntity kingInquiryEntity) {
        if ( StringUtils.isBlank ( kingInquiryEntity.getId () ) ) {
            return AjaxResult.error ("请先暂存该单据！");
        }
        //启动审批流程
        StartProcessDto startDto = new StartProcessDto().setBusinessId(kingInquiryEntity.getId()).setBusinessType(kingInquiryEntity.getBusinessType()).setModelId(kingInquiryEntity.getModelId());
        startDto.setBusinessName("询/报价单_".concat(kingInquiryEntity.getId ()));
        String instanceId = actModelService.startProcess(startDto);
        boolean save = this.update ( new LambdaUpdateWrapper<KingInquiryEntity>().
                set ( KingInquiryEntity :: getState, ConstUtil.STATE_IN_PROCESS ).
                set ( KingInquiryEntity :: getInstanceId, instanceId ).
                eq ( KingInquiryEntity :: getId, kingInquiryEntity.getId () ) );
        if ( !save ) {
            throw new CustomException( "提交失败!" );
        }
        return AjaxResult.success ( "提交成功!" );
    }

    /**
     * 查询金蝶-询价/报价单
     *
     * @param id 金蝶-询价/报价单ID
     * @return 金蝶-询价/报价单
     */
    @Override
    public KingInquiryEntity selectKingInquiryEntityById(String id)
    {
        KingInquiryEntity kingInquiryEntity = kingInquiryMapper.selectKingInquiryEntityById(id);
        if(Objects.nonNull(kingInquiryEntity)){
            List<KingInquirySupplierEntity> inquirySupplierList = inquirySupplierService.list(new QueryWrapper<KingInquirySupplierEntity>().eq("inquiry_id", kingInquiryEntity.getId()));
            kingInquiryEntity.setInquirySupplierList(inquirySupplierList);
            List<KingInquiryQuotationEntity> inquiryQuotationList = inquiryQuotationService.list(new QueryWrapper<KingInquiryQuotationEntity>().eq("inquiry_id", kingInquiryEntity.getId()));
            kingInquiryEntity.setInquiryQuotationList(inquiryQuotationList);
            List<KingInquiryDetailEntity> inquiryDetailList = inquiryDetailService.list(new QueryWrapper<KingInquiryDetailEntity>().eq("inquiry_id", kingInquiryEntity.getId()));
            if(!CollectionUtils.isEmpty(inquiryDetailList)){
                inquiryDetailList.forEach(inquiryDetail -> {
                    KingInquiryDetailEntryEntity inquiryDetailEntryEntity = inquiryDetailEntryService.getOne(new QueryWrapper<KingInquiryDetailEntryEntity>().eq("inquiry_id", kingInquiryEntity.getId()).eq("detail_id", inquiryDetail.getId()));
                    inquiryDetail.setInquiryDetailEntry(inquiryDetailEntryEntity);
                });
            }
            kingInquiryEntity.setInquiryDetailList(inquiryDetailList);
            //结算币别名称
            if(!StringUtils.isEmpty(kingInquiryEntity.getSettlementCurrency())){
                KingBaseCurrencyEntity currency = currencyService.getById(kingInquiryEntity.getSettlementCurrency());
                if(Objects.nonNull(currency)){
                    kingInquiryEntity.setSettlementCurrencyName(currency.getCurrencyName());
                }
            }
        }
        return kingInquiryEntity;
    }

    /**
     * 查询金蝶-询价/报价单列表
     *
     * @param kingInquiryEntity 金蝶-询价/报价单
     * @return 金蝶-询价/报价单
     */
    @Override
    public List<KingInquiryEntity> selectKingInquiryEntityList(KingInquiryEntity kingInquiryEntity)
    {
        List<KingInquiryEntity> kingInquiryList = kingInquiryMapper.selectKingInquiryEntityList(kingInquiryEntity);
        if(!CollectionUtils.isEmpty(kingInquiryList)){
            kingInquiryList.forEach(inquiryEntity -> {
                List<KingInquirySupplierEntity> inquirySupplierList = inquirySupplierService.list(new QueryWrapper<KingInquirySupplierEntity>().eq("inquiry_id", inquiryEntity.getId()));
                inquiryEntity.setInquirySupplierList(inquirySupplierList);
                List<KingInquiryQuotationEntity> inquiryQuotationList = inquiryQuotationService.list(new QueryWrapper<KingInquiryQuotationEntity>().eq("inquiry_id", inquiryEntity.getId()));
                inquiryEntity.setInquiryQuotationList(inquiryQuotationList);
                List<KingInquiryDetailEntity> inquiryDetailList = inquiryDetailService.list(new QueryWrapper<KingInquiryDetailEntity>().eq("inquiry_id", inquiryEntity.getId()));
                if(!CollectionUtils.isEmpty(inquiryDetailList)){
                    inquiryDetailList.forEach(inquiryDetail -> {
                        KingInquiryDetailEntryEntity inquiryDetailEntryEntity = inquiryDetailEntryService.getOne(new QueryWrapper<KingInquiryDetailEntryEntity>().eq("inquiry_id", inquiryEntity.getId()).eq("detail_id", inquiryDetail.getId()));
                        inquiryDetail.setInquiryDetailEntry(inquiryDetailEntryEntity);
                    });
                }
                inquiryEntity.setInquiryDetailList(inquiryDetailList);
            });
        }
        return kingInquiryList;
    }

    /**
     * 修改金蝶-询价/报价单
     *
     * @param kingInquiryEntity 金蝶-询价/报价单
     * @return 结果
     */
    @Override
    public int updateKingInquiryEntity(KingInquiryEntity kingInquiryEntity)
    {
        //保存适用供应商信息
        inquirySupplierService.remove(new QueryWrapper<KingInquirySupplierEntity>().eq("inquiry_id",kingInquiryEntity.getId()));
        if(!CollectionUtils.isEmpty(kingInquiryEntity.getInquirySupplierList())){
            List<KingInquirySupplierEntity> inquirySupplierList = kingInquiryEntity.getInquirySupplierList();
            for(KingInquirySupplierEntity inquirySupplier : inquirySupplierList){
                inquirySupplier.setId(SnowflakeIdWorker.getInstance().nextStringId());
                inquirySupplier.setInquiryId(kingInquiryEntity.getId());
                boolean save = inquirySupplierService.save(inquirySupplier);
                if(!save){
                    throw new RuntimeException("更新询价/报价单适用供应商信息失败！");
                }
            }
        }
        //保存报价采纳信息
        inquiryQuotationService.remove(new QueryWrapper<KingInquiryQuotationEntity>().eq("inquiry_id",kingInquiryEntity.getId()));
        if(!CollectionUtils.isEmpty(kingInquiryEntity.getInquiryQuotationList())){
            List<KingInquiryQuotationEntity> inquiryQuotationList = kingInquiryEntity.getInquiryQuotationList();
            for(KingInquiryQuotationEntity inquiryQuotation : inquiryQuotationList){
                inquiryQuotation.setId(SnowflakeIdWorker.getInstance().nextStringId());
                inquiryQuotation.setInquiryId(kingInquiryEntity.getId());
                boolean save = inquiryQuotationService.save(inquiryQuotation);
                if(!save){
                    throw new RuntimeException("更新询价/报价单报价采纳信息失败！");
                }
            }
        }
        //保存物料明细信息
        inquiryDetailService.remove(new QueryWrapper<KingInquiryDetailEntity>().eq("inquiry_id",kingInquiryEntity.getId()));
        inquiryDetailEntryService.remove(new QueryWrapper<KingInquiryDetailEntryEntity>().eq("inquiry_id",kingInquiryEntity.getId()));
        List<KingInquiryDetailEntity> inquiryDetailList = kingInquiryEntity.getInquiryDetailList();
        for(KingInquiryDetailEntity inquiryDetail : inquiryDetailList){
            String inquiryDetailId = SnowflakeIdWorker.getInstance().nextStringId();
            inquiryDetail.setInquiryId(kingInquiryEntity.getId());
            inquiryDetail.setId(inquiryDetailId);
            inquiryDetail.setType(kingInquiryEntity.getType());
            boolean save = inquiryDetailService.save(inquiryDetail);
            if(save){
                if(Objects.nonNull(inquiryDetail.getInquiryDetailEntry())){
                    KingInquiryDetailEntryEntity inquiryDetailEntry = inquiryDetail.getInquiryDetailEntry();
                    inquiryDetailEntry.setId(SnowflakeIdWorker.getInstance().nextStringId());
                    inquiryDetailEntry.setInquiryId(kingInquiryEntity.getId());
                    inquiryDetailEntry.setDetailId(inquiryDetailId);
                    inquiryDetailEntryService.save(inquiryDetailEntry);
                }
            }else {
                throw new RuntimeException("更新询价/报价单物料明细信息失败！");
            }
        }
        kingInquiryEntity.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserId());
        kingInquiryEntity.setUpdateTime(DateUtils.getNowDate());
        return kingInquiryMapper.updateKingInquiryEntity(kingInquiryEntity);
    }

    /**
     * 批量删除金蝶-询价/报价单
     *
     * @param ids 需要删除的金蝶-询价/报价单ID
     * @return 结果
     */
    @Override
    public int deleteKingInquiryEntityByIds(String[] ids)
    {
        for(String id : ids){
            inquirySupplierService.remove(new QueryWrapper<KingInquirySupplierEntity>().eq("inquiry_id",id));
            inquiryQuotationService.remove(new QueryWrapper<KingInquiryQuotationEntity>().eq("inquiry_id",id));
            inquiryDetailService.remove(new QueryWrapper<KingInquiryDetailEntity>().eq("inquiry_id",id));
            inquiryDetailEntryService.remove(new QueryWrapper<KingInquiryDetailEntryEntity>().eq("inquiry_id",id));
        }
        return kingInquiryMapper.deleteKingInquiryEntityByIds(ids);
    }

    /**
     * 删除金蝶-询价/报价单信息
     *
     * @param id 金蝶-询价/报价单ID
     * @return 结果
     */
    @Override
    public int deleteKingInquiryEntityById(String id)
    {
        inquirySupplierService.remove(new QueryWrapper<KingInquirySupplierEntity>().eq("inquiry_id",id));
        inquiryQuotationService.remove(new QueryWrapper<KingInquiryQuotationEntity>().eq("inquiry_id",id));
        inquiryDetailService.remove(new QueryWrapper<KingInquiryDetailEntity>().eq("inquiry_id",id));
        inquiryDetailEntryService.remove(new QueryWrapper<KingInquiryDetailEntryEntity>().eq("inquiry_id",id));
        return kingInquiryMapper.deleteKingInquiryEntityById(id);
    }

    @Override
    public AjaxResult getKingInquiryPageList(KingInquiryQueryDto queryDto){
        List<KingInquiryVo> list = inquiryDetailService.getKingInquiryPageList(queryDto);
        if(!CollectionUtils.isEmpty(list)){
            list.forEach(kingInquiryVo -> {
                ActTaskCommentEntity actTaskCommentEntity = actTaskCommentService.queryLastComment(kingInquiryVo.getInstanceId());
                if ( actTaskCommentEntity != null ) {
                    kingInquiryVo.setApprovedUser ( actTaskCommentEntity.getApprovedUser () );
                    kingInquiryVo.setRemark ( actTaskCommentEntity.getRemark () );
                }
                ActCurrentTaskVo currentTaskVo = actModelService.getCurrentTaskByInstanceId(kingInquiryVo.getInstanceId());
                Optional.ofNullable(currentTaskVo).ifPresent(kingInquiryVo::setCurrentTask);
            });
        }
        Page<KingInquiryVo> page = new Page<>(queryDto.getPage(),queryDto.getLimit());
        return AjaxResult.success ( ReturnPage.getReturnPage ( page, list ) );
    }

    @Override
    public AjaxResult getKingInquiryOfferPageList(KingInquiryQueryDto queryDto) {
        List<KingInquiryOfferVo> list = inquiryDetailService.getKingInquiryOfferPageList(queryDto);
        if(!CollectionUtils.isEmpty(list)){
            list.forEach(kingInquiryOfferVo -> {
                ActTaskCommentEntity actTaskCommentEntity = actTaskCommentService.queryLastComment(kingInquiryOfferVo.getInstanceId());
                if ( actTaskCommentEntity != null ) {
                    kingInquiryOfferVo.setApprovedUser ( actTaskCommentEntity.getApprovedUser () );
                    kingInquiryOfferVo.setRemark ( actTaskCommentEntity.getRemark () );
                }
                ActCurrentTaskVo currentTaskVo = actModelService.getCurrentTaskByInstanceId(kingInquiryOfferVo.getInstanceId());
                Optional.ofNullable(currentTaskVo).ifPresent(kingInquiryOfferVo::setCurrentTask);
            });
        }
        Page<KingInquiryOfferVo> page = new Page<>(queryDto.getPage(),queryDto.getLimit());
        return AjaxResult.success ( ReturnPage.getReturnPage ( page, list ) );
    }

}
